package com.xujie.chat.server.manager;

import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

import static com.xujie.chat.message.NettyConstant.CLIENT_ID_KEY;

/**
 * 类说明：客户端管理类
 *
 * @author Xujie
 * @since 2024/12/29 13:14
 **/


public class ClientManager {
	private static final ConcurrentMap<String, Channel> channelMap = new ConcurrentHashMap<>();
	private static final AtomicInteger counter = new AtomicInteger(0);

	public static void addClient(String clientId, Channel channel) {
		channelMap.put(clientId, channel);
	}
	public static String addClient(Channel channel) {
		String clientId = String.valueOf(counter.addAndGet(1));
		channel.attr(CLIENT_ID_KEY).set(clientId);
		channelMap.put(clientId, channel);
		return clientId;
	}

	public static Channel getChannel(String clientId) {
		return channelMap.get(clientId);
	}

	public static void removeClient(String clientId) {
		channelMap.remove(clientId);
	}

	public static Integer getClientNum() {
		return channelMap.size();
	}

	public static String getOnlineClients(String clientId) {
		StringBuilder sb = new StringBuilder();
		sb.append("客户端总数：").append(channelMap.size()).append("\n");
		channelMap.forEach((k, v) -> {
			if (!k.equals(clientId)) {
				sb.append("客户端ID：").append(k).append("\n");
			} else {
				sb.append("客户端ID：").append(k).append("（自己）\n");
			}
		});
		return sb.toString();
	}

	public static void sendMsg(String clientId, String toClientId, Object body) {
		Channel channel = channelMap.get(toClientId);
		if (channel != null && channel.isActive()) {
			channel.writeAndFlush(buildMessage(clientId, toClientId, body.toString()));
		} else {
			Channel byChannel = channelMap.get(clientId);
			byChannel.writeAndFlush(buildMessage(clientId, clientId, "对方不在线"));
		}
	}

	private static MyMessage buildMessage(String clientId, String toClientId, String body) {
		MyMessage message = new MyMessage();
		MsgHeader msgHeader = new MsgHeader();
		msgHeader.setType(MessageType.MESSAGE.value());
		msgHeader.setClientId(toClientId);
		msgHeader.setByClientId(clientId);
		message.setMyHeader(msgHeader);
		message.setBody(body);
		return message;
	}
}
